<?php

namespace app\controller;

use app\BaseController;
use app\service\BigService;
use app\Request;
use app\service\ImageService;
use mysql_xdevapi\Exception;
use think\facade\Config;
use think\Response;
use think\facade\Log;
use think\App;

class Index extends BaseController
{
    protected $bigServiec;
    protected $r; //Request 对象

    protected $imageService;

    public function __construct(BigService $bigServiec, Request $r, ImageService $imageService)
    {
        $this->bigServiec = $bigServiec;
        $this->r = $r;
        //$this->customMethod($r);
        $this->imageService = $imageService;
    }

    public function index()
        //https://www.kancloud.cn/a173512/thinkphp6/1327360
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">16载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }


    //设置
    public function settime(Request $request)
    {
        $og = $request->post();
        $arr['controller'] = 'settime';
        $time = $og['time'];
        Config::set(['settime' => $time], 'time');
        $arr['time'] = '你设置了轮播秒数' . $time;
        $arr['config'] = Config::get('time');
        return json($arr);
    }

    public function fetchtime(Request $request)
    {
        $og = $request->post();
        $arr['controller'] = 'fetchtime';
        $arr['config'] = Config::get('time');
        return json($arr);
    }


    //texttime
    public function iotimeget(Request $request)
    {
        $file = './time.txt';
        $content = file_get_contents($file);
        $arr['time'] = $content;
        return json($arr);
    }

    public function codeget(Request $request)
    {
        $timestamp = time();
        $currentHour = date('G', $timestamp);
        $arr['cc'] = $currentHour; //17
        $arr['bigcode'] = md5($currentHour);

        return json($arr);
    }

    public function iotimeset(Request $request)
    {
        $og = $request->post();
        $time = $og['time'];
        $arr['controller'] = "iotimeset";
        $file = './time.txt';
        $handle = fopen($file, 'c');
        $content = $time;
        file_put_contents($file, $time);
        return json($arr);
    }


    public function bigshow(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $themeid = $og['themeid'];
        $arr = $this->bigServiec->bigshow($uniacid, $id, $themeid);
        $arr['og'] = $og;
        return json($arr);
    }

    public function bignewpaynum(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $themeid = $og['themeid'];
        $arr = $this->bigServiec->findHomeOrderNum($uniacid, $id, $themeid);
        $arr['og'] = $og;
        return json($arr);
    }


    /**
     * 1.活动标题
     */
    public function activitietitle(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->activitietitle($uniacid, $id);
        $arr['og'] = $og;
        return json($arr);
    }

    //ordersum
    //订单总量
    public function ordersum(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->ordersum($uniacid, $id);
        $arr['og'] = $og;
        return json($arr);
    }

    //倒计时 countdown
    public function countdown(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->countdown($uniacid, $id);
        $arr['og'] = $og;
        return json($arr);
    }

    //fullgourp
    public function fullgourp(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->fullgourp($uniacid, $id);
        $arr['og'] = $og;
        $arr['action'] = 'fullgourp';
        return json($arr);
    }


    //6 准客，即未支付的 zhuncus
    //record
    //ut
    public function zhuncus(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $arr = $this->bigServiec->zhuncus($uniacid, $themeid);
        return json($arr);
    }

    //7 访客 ui
    public function fanssum(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->fanssum($uniacid, $id);
        return json($arr);
    }

    //ui
    public function ui(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $id = $og['id'];
        $arr = $this->bigServiec->ui($uniacid, $id);
        $arr['og'] = $og;
        return json($arr);
    }

    //ut
    public function ut(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $arr = $this->bigServiec->ut($uniacid, $themeid);
        $arr['og'] = $og;
        $arr['action'] = 'ut';
        return json($arr);
    }

    //8-9 新客数量和老客数量
    //newcus 新客数量
    public function newoldcus(Request $request)
    {
        //入参是小程序post过来的
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $newold = '老';
        $arr = $this->bigServiec->newoldcus($uniacid, $themeid, $newold);
        $arr['og'] = $og;
        $arr['action'] = 'newoldcus';
        return json($arr);
    }

    //10已支付
    //payon 主要是ut
    public function payon(Request $request)
    {
        //同时三个入参
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        //先做已支付
        $arr = $this->bigServiec->payon($uniacid, $themeid);
        $arr['og'] = $og;
        $arr['action'] = 'payon';
        return json($arr);
    }

    //11 未支付
    //payoff 主要是ui
    public function payoff(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        //其实是访客
        $arr = $this->bigServiec->payoff($uniacid, $themeid, $id);
        $arr['og'] = $og;
        $arr['action'] = 'payoff';
        return json($arr);
    }

    //员工排行
    public function cusanking(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr['og'] = $og;
        $arr['action'] = 'cusanking';
        $arr = $this->bigServiec->cusanking($uniacid, $themeid, $id);
        return json($arr);
    }

    //员工表
    public function worker(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr['og'] = $og;
        $arr['action'] = 'worker';
        $arr = $this->bigServiec->worker($uniacid, $themeid, $id);
        return json($arr);
    }

    public function fans(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr = $this->bigServiec->fans($uniacid, $themeid, $id);
        return json($arr);
    }

    public function workertop(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr['og'] = $og;
        $arr['action'] = 'worker';
        $arr = $this->bigServiec->workertop($uniacid, $themeid, $id);
        return json($arr);
    }

    //团队排行
    public function grouptop(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr['controller'] = 'grouptop';
        $arr = $this->bigServiec->grouptop($uniacid, $themeid, $id);
        return json($arr);
    }

    //红包排行
    public function redtop(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $arr['controller'] = 'redtop';
        $arr = $this->bigServiec->redtop($uniacid, $themeid);
        return json($arr);
    }

    //事件大屏
    public function eventslist(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $arr['controller'] = 'eventslist';
        $arr = $this->bigServiec->eventslist($uniacid, $themeid);
        return json($arr);
    }

    public function testfun(Request $request)
    {
        $og = $request->post();
        $arr['controller'] = $og;
        $array = [1, 2, 3, 4, 5, "a"];
        $slicedArray = array_slice($array, 0, 2);
        $arr['one'] = $slicedArray;
        // 1  2   3   4
        // 0  1   2   3
        $arr['two'] = array_slice($array, 2, count($array) - 2);
        //算法2
        $timestamp = time();
        $currentHour = date('G', $timestamp);
        //echo "当前时间是 $currentHour 点";
        $arr['cc'] = $currentHour; //17
        $arr['bigcode'] = md5($currentHour);
        return json($arr);
    }

    public function codeauth($bigcode)
    {
        $timestamp = time();
        $currentHour = date('G', $timestamp);
        $apicode = md5($currentHour);
        if ($bigcode == $apicode) {
            return true;
        }
        return false;
    }

    //findOrder
    public function findbyopen(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $openid = $og['openid'];
        $arr['controller'] = 'findOrder';
        $arr = $this->bigServiec->findOrder($uniacid, $themeid, $openid);
        return json($arr);
    }

    public function findbysn(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $sn = $og['sn'];
        $arr['controller'] = 'findbysn';
        $arr = $this->bigServiec->findbysn($uniacid, $themeid, $sn);
        return json($arr);
    }

    public function findbyrr(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $rr = $og['rr'];
        $arr['controller'] = 'findbyrr';
        $arr = $this->bigServiec->findbyrr($uniacid, $themeid, $rr);
        return json($arr);
    }

    //
    public function findbthemebyid(Request $request)
    {
        $og = $request->post();

        $themeid = $og['themeid'];
        $arr['controller'] = 'findbthemebyid';
        $arr = $this->bigServiec->findbthemebyid($themeid);
        return json($arr);
    }

    public function testime(Request $request)
    {
        $og = $request->post();
        $str = $og['sql'];
        $arr['controller'] = 'testime';
        $arr = $this->bigServiec->testime($str);
        return json($arr);
    }

    public function yutest(Request $request)
    {
//        $arr['a']='a';
//        return json($arr);
        $og = $request->post();
        $text = $og['text'];
        $AppKey = "7f10bd2f882145a5b2ed1402b3b20eba";
        $AppSecret = "55643bdb52c74f2e9c269d34ba171b6f";

        $cty = new Cty();
        $url = "https://ai-global.ctapi.ctyun.cn" . "/v1/aiop/api/2z0yhhrzgv0g/tts/predict";

        $header = array();
        $header['appkey'] = 'c0b71c83e6ae902d68d9334e6410fb1c';

        if (isset($og['text'])) {
            $text = $og['text'];

        } else {
            $text = "今晚去吃火锅吗哈哈";
        }


        $body["Action"] = 'TTS';
        $body["TextData"] = $text;

        //$body = "{\"Action\": \"TTS\", \"TextData\": \"今晚去吃火锅吗\"}";

        $fileMap = array();
        $res = $cty->ctyun($AppSecret, $AppKey, $url, null, $header, $body, "POST", "application/json", null);

        return $res;
    }

    public function yuyinorderlist(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr = $this->bigServiec->tentopOrder($uniacid, $themeid);
        $len = count($arr);
        //便利数组
        $filteredData = array();
        $arr['$len_1'] = count($filteredData);
        $sqldata = $arr['sqldata'];
        foreach ($sqldata as $item) {
            // if (!is_null($item['username'])) {
            if (isset($item['username']) && $item['username'] !== null) {
                //$filteredData[$key] = $item;
                array_push($filteredData, $item);
            }
        }
        $arr['sqldata'] = $sqldata;
        $arr['$len_2'] = count($filteredData);
        $arr['controller'] = 'yuyinlist';
        $arr['len'] = $len;

        return json($arr);
    }

    public function yuyinone(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $recordid = $og['recordid'];
        $arr = $this->bigServiec->yuyinone($uniacid, $themeid, $recordid);
        $len = count($arr);
        //便利数组
        $filteredData = array();
        if (isset($arr['sqldata'])) {
            $sqldata = $arr['sqldata'];
            foreach ($sqldata as $item) {
                // if (!is_null($item['username'])) {
                //if (isset($item['username']) && $item['username'] !== null) {
                //$filteredData[$key] = $item;
                array_push($filteredData, $item);
                //}
            }
            //unset($arr['sqldata']);
            //todo
            $this->getbasestr($filteredData);
        } else {
            $arr['备注'] = "没有数据";
        }
        $arr['$len_2'] = count($filteredData);
        $arr['controller'] = 'yuyinlist';
        $arr['len'] = $len;
        $arr['new_data'] = $filteredData;
        return json($arr);

    }


    //比如10个订单
    public function yuyinlist(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $id = $og['id'];
        $arr = $this->bigServiec->tentopOrder($uniacid, $themeid);
        $len = count($arr);
        //便利数组
        $filteredData = array();
        $arr['$len_1'] = count($filteredData);
        $sqldata = $arr['sqldata'];

        foreach ($sqldata as $item) {
            // if (!is_null($item['username'])) {
            //if (isset($item['username']) && $item['username'] !== null) {
            //$filteredData[$key] = $item;
            array_push($filteredData, $item);
            //}
        }
        //todo
        $this->getbasestr($filteredData);
        unset($arr['sqldata']);
        $arr['$len_2'] = count($filteredData);
        $arr['controller'] = 'yuyinlist';
        $arr['len'] = $len;
        $arr['new_data'] = $filteredData;

        return json($arr);
    }

    public function t3()
    {
        //https://back.screen.cmxz.com.cn/index.php/t3
        $AppKey = "7f10bd2f882145a5b2ed1402b3b20eba";
        $AppSecret = "55643bdb52c74f2e9c269d34ba171b6f";
        $cty = new Cty();
        $url = "https://ai-global.ctapi.ctyun.cn" . "/v1/aiop/api/2z0yhhrzgv0g/tts/predict";
        $header = array();
        $header['appkey'] = 'c0b71c83e6ae902d68d9334e6410fb1c';
        $body["Action"] = 'TTS';
        $body["TextData"] = '今晚吃火锅';
        //$body = "{\"Action\": \"TTS\", \"TextData\": \"今晚去吃火锅吗\"}";
        $fileMap = array();
        $res = $cty->ctyun($AppSecret, $AppKey, $url, null, $header, $body, "POST", "application/json", null);

        $result = $res["returnObj"];

        $filePath = 'output.mp3';
        $audio_wav_dd = $this->urlSafeBase64Decode($result["Audio"]);
        file_put_contents($filePath, $audio_wav_dd);


        $audio_wav_dd = $this->urlSafeBase64Decode($result["Audio"]);
        $mp3_base64_u1 = base64_encode($audio_wav_dd);
        //$arr['audio'] = $mp3_base64_u1;
        $arr['t3'] = $filePath;
        return json($arr);
    }


    public function test(Request $request)
    {
        //$word = $request->get("word");
        $word = $request->param('word');
        $AppKey = "7f10bd2f882145a5b2ed1402b3b20eba";
        $AppSecret = "55643bdb52c74f2e9c269d34ba171b6f";

        $cty = new Cty();
        $url = "https://ai-global.ctapi.ctyun.cn" . "/v1/aiop/api/2z0yhhrzgv0g/tts/predict";

        $header = array();
        $header['appkey'] = 'c0b71c83e6ae902d68d9334e6410fb1c';
        $body["Action"] = 'TTS';
        $body["TextData"] = $word;

        //$body = "{\"Action\": \"TTS\", \"TextData\": \"今晚去吃火锅吗\"}";

        $fileMap = array();
        $res = $cty->ctyun($AppSecret, $AppKey, $url, null, $header, $body, "POST", "application/json", null);

        $result = $res["returnObj"];
        //audio_wav_dd = base64.urlsafe_b64decode(result["Audio"])
        //print("audio base64 len:{}".format(len(audio_wav_dd)))
        $audio_wav_dd = $this->urlSafeBase64Decode($result["Audio"]);
        $mp3_base64_u1 = base64_encode($audio_wav_dd);
        $arr['audio'] = $mp3_base64_u1;
        return json($arr);

    }

    public function getbasestr(&$arr)
    {
        $AppKey = "7f10bd2f882145a5b2ed1402b3b20eba";
        $AppSecret = "55643bdb52c74f2e9c269d34ba171b6f";
        $cty = new Cty();
        $url = "https://ai-global.ctapi.ctyun.cn" . "/v1/aiop/api/2z0yhhrzgv0g/tts/predict";

        $header = array();
        $header['appkey'] = 'c0b71c83e6ae902d68d9334e6410fb1c';

        foreach ($arr as &$item) {
            $body = array();
            $body["Action"] = 'TTS';
            //$body["TextData"] = $item['username'] . "  有新的订单已支付请及时处理";
            //来源员工”，您的客户“关联订单”已下单，请及时处理
            if (isset($item['username']) && $item['username'] !== null) {
                $body["TextData"] = $item['username'] . ",您的客户 " . $item['guanlian_username'] . "已下单，请及时处理";
            } else {
                $body["TextData"] = "客户 " . $item['guanlian_username'] . "已下单，请及时处理";
            }
            $body["VoiceType"] = 1;
            $res = $cty->ctyun($AppSecret, $AppKey, $url, null, $header, $body, "POST", "application/json", null);
            $result = $res["returnObj"];
            //audio_wav_dd = base64.urlsafe_b64decode(result["Audio"])
            //print("audio base64 len:{}".format(len(audio_wav_dd)))
            $audio_wav_dd = $this->urlSafeBase64Decode($result["Audio"]);
            $str = base64_encode($audio_wav_dd);
            $item['audio'] = $str;

            unset($body);
        }
        unset($item);
    }


    function urlSafeBase64Decode($data)
    {
        // 将 URL 安全的 Base64 字符替换回标准 Base64 字符
        $data = strtr($data, '-_', '+/');

        // 添加缺失的填充字符，确保长度为4的倍数
        $mod4 = strlen($data) % 4;
        if ($mod4 > 0) {
            $data .= substr('====', $mod4);
        }

        // 使用标准 base64_decode 进行解码
        return base64_decode($data);
    }

    //增加滚动速率 5个档位 默认在第3档位
    public function playspeed(Request $request)
    {
        $speed = [1, 2, 3, 4, 5];
        $speedtxt = ["极慢", "慢", "正常", "快", "极快"];
        $cur = 3;
        $arr['speed'] = $speed;
        $arr['speedtxt'] = $speedtxt;
        $arr['cur'] = $cur;
        return json($arr);
    }

    public function onetts(Request $request)
    {
        $og = $request->post();
        if (isset($og['word'])) {
            $word = $og['word'];
        } else {
            $word = "欢迎光临";
        }
        $AppKey = "7f10bd2f882145a5b2ed1402b3b20eba";
        $AppSecret = "55643bdb52c74f2e9c269d34ba171b6f";
        $cty = new Cty();
        $url = "https://ai-global.ctapi.ctyun.cn" . "/v1/aiop/api/2z0yhhrzgv0g/tts/predict";
        $header = array();
        $header['appkey'] = 'c0b71c83e6ae902d68d9334e6410fb1c';
        $body = array();
        $body["Action"] = 'TTS';
        $body["TextData"] = $word;
        $body["VoiceType"] = 1;
        $res = $cty->ctyun($AppSecret, $AppKey, $url, null, $header, $body, "POST", "application/json", null);
        $result = $res["returnObj"];
        $audio_wav_dd = $this->urlSafeBase64Decode($result["Audio"]);
        $str = base64_encode($audio_wav_dd);
        $item['audio'] = $str;
        return json($item);
    }


    public function fetchpnames(Request $request)
    {
        $og = $request->post();
        $pids = $og['pids'];
        if (is_array($pids)) {
            $arr['flag'] = 'true';
        } else {
            $arr['flag'] = 'false';
        }

        $arr = $this->bigServiec->fetchpnames($pids);
        return json($arr);
    }

    public function phpfun()
    {
        //phpinfo();
        $arr['info'] = phpinfo();
        return $arr;
    }

    public function getheadlogo()
    {
        //ims_water_salegroup3_config
        //DB平台uniacid  和活动aid
    }

    public function haibao2(Request $request)
    {
        //step_01 获取头像
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");
        $openid = $request->get('openid');


        //findhaibao
        $arr_touxiang = $this->bigServiec->findhaibao_touxiang($uniacid, $themeid, $openid);
        var_dump($arr_touxiang);
        return 333;
        $len = count($arr_touxiang['sqldata']);
        if ($len > 0) {
            $avatar_url = $arr_touxiang['sqldata'][0]['avatar'];
            echo $avatar_url;
        }
        if (!isset($avatar_url)) {
            echo "DB没有头像";
            return 1111;
        } else {
            //echo $avatar_url;
            return $avatar_url;
        }


    }

    public function haibao(Request $request)
    {
        //step_01 获取头像
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");
        $openid = $request->get('openid');

        //findhaibao
        $arr_touxiang = $this->bigServiec->findhaibao_touxiang($uniacid, $themeid, $openid);
        $len = count($arr_touxiang['sqldata']);
        if ($len > 0) {
            $avatar_url = $arr_touxiang['sqldata'][0]['avatar'];
            //echo $avatar;
        }
        if (!isset($avatar_url)) {
            echo "DB没有头像";
            return 1111;
        } else {
            //echo $avatar_url;
        }

        $arr_head = $this->bigServiec->findhaibao_config($uniacid, $themeid);
        $len2 = count($arr_head['sqldata']);
        if ($len2 > 0) {
            $value = $arr_head['sqldata'][0]['value'];
        }
        if (!isset($value)) {
            echo "DB活动配置没有";
        }
        $arr_value = unserialize($value);

        $headdb = $arr_value['headlogo'];
        $head_url = "https://tuan.cmzg.vip/" . $headdb;

        $api_url = "https://cm.cmzg.vip/app/index.php?i=$uniacid&c=entry&themeid=$themeid&openid=$openid&do=api_qrcode&m=water_salegroup3";
        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');
        $jsonObject = json_decode($http_data);

        $arr_message = $jsonObject->message;
        if ($arr_message->msg == "success") {  //Cannot use object of type stdClass as array
            //echo "http api 有二维码";
            $qrcode_url = $arr_message->qrcode;
        } else {
            echo "http api 没有二维码";
        }
        if (isset($qrcode_url)) {
            //echo  $qrcode_url;

        }
//        $r['$head_url']= $head_url;
//        $r['$http_data']= $http_data;
//        return json_encode($r);
        try {
            //$baseImageUrl = 'https://cm.cmzg.vip/addons/water_salegroup3/data/poster/24/5260/a0dce8b9e00d06b63bdedda266c80732.png';
            $baseImageUrl = $head_url;
            $overlayImageUrls = [
                //"https://tuan.cmzg.vip/images/water_salegroup3/20241107132339_5433906773_2964.jpeg", //头像
                $avatar_url,
                $qrcode_url
            ];
            // 定义每个叠加图的位置


            $positions = [
                'bottom-left', //top-left改 bottom-left
//                'top-right',
                'bottom-right'
            ];
            // 调用服务方法
            $this->imageService->mergeMultipleImagesToBrowser2($baseImageUrl, $overlayImageUrls, $positions);
            // 返回图像数据
            header("Content-Type: image/png; charset=utf-8");
            echo $baseImageUrl;
            exit;
            // 获取缓冲区内容并清除缓冲区
            //$imageData = ob_get_clean();

        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }

    }


    public function haibao_001(Request $request)
    {
        //step_01 获取头像
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");
        $openid = $request->get('openid');

        //findhaibao
        $arr_touxiang = $this->bigServiec->findhaibao_touxiang($uniacid, $themeid, $openid);
        $len = count($arr_touxiang['sqldata']);
        if ($len > 0) {
            $avatar_url = $arr_touxiang['sqldata'][0]['avatar'];
            //echo $avatar;
        }
        if (!isset($avatar_url)) {
            echo "DB没有头像";
        } else {
            //echo $avatar_url;
        }

        $arr_head = $this->bigServiec->findhaibao_config($uniacid, $themeid);
        $len2 = count($arr_head['sqldata']);
        if ($len2 > 0) {
            $value = $arr_head['sqldata'][0]['value'];
        }
        if (!isset($value)) {
            echo "DB活动配置没有";
        }
        $arr_value = unserialize($value);

        $headdb = $arr_value['headlogo'];
        $head_url = "https://tuan.cmzg.vip/" . $headdb;
        //echo "---";
        //echo $head_url;

        //抓一个接口图
//        $uniacid = 117;
//        $themeid= 7613;
        $api_url = "https://cm.cmzg.vip/app/index.php?i=$uniacid&c=entry&themeid=$themeid&openid=$openid&do=api_qrcode&m=water_salegroup3";
        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');
        $jsonObject = json_decode($http_data);

        $arr_message = $jsonObject->message;
        if ($arr_message->msg == "success") {  //Cannot use object of type stdClass as array
            //echo "http api 有二维码";
            $qrcode_url = $arr_message->qrcode;
        } else {
            echo "http api 没有二维码";
        }
        if (isset($qrcode_url)) {
            //echo  $qrcode_url;

        }

        try {
            //$baseImageUrl = 'https://cm.cmzg.vip/addons/water_salegroup3/data/poster/24/5260/a0dce8b9e00d06b63bdedda266c80732.png';
            $baseImageUrl = $head_url;
            $overlayImageUrls = [
                //"https://tuan.cmzg.vip/images/water_salegroup3/20241107132339_5433906773_2964.jpeg", //头像
                $avatar_url,
                $qrcode_url
            ];
            // 定义每个叠加图的位置


            $positions = [
                'bottom-left', //top-left改 bottom-left
//                'top-right',
                'bottom-right'
            ];
            // 调用服务方法
            $this->imageService->mergeMultipleImagesToBrowser($baseImageUrl, $overlayImageUrls, $positions);
            // 返回图像数据
            header("Content-Type: image/png; charset=utf-8");
            echo $baseImageUrl;
            exit;
            // 获取缓冲区内容并清除缓冲区
            //$imageData = ob_get_clean();

        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    function curl_request($url, $method = 'get', $params = [], $header = [], $type = 'http')
    {
        /**
         * 初始化curl，返回资源
         */
        $curl = curl_init($url);
        /**
         * 默认是get请求，如果是post/put请求，设置请求方式和请求参数
         */
        if (strtoupper($method) == 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        if (strtoupper($method) == 'PUT') {
            curl_setopt($curl, CURLOPT_PUT, true);
        }
        /**
         * 设置header头部传参
         */
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        /**
         * 如果是HTTPS协议，禁止从服务器验证本地证书
         */
        if (strtoupper($type) == 'HTTPS') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        /**
         * 超时设置，单位毫秒
         */
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 10000);
        /**
         * 发送请求，返回结果
         */
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        /**
         * 不验证ssl
         */
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        /**
         * 选择地址
         * curl_setopt($curl,CURLOPT_URL,$url);
         */
        $res = curl_exec($curl);

        if ($res === false) {
            $error = curl_error($curl);
            curl_close($curl);
            // 抛出一个异常或返回错误信息
            throw new Exception("CURL Error: " . $error);
        }

        /**
         * 关闭请求
         */
        curl_close($curl);
        return $res;

    }

    public function findconfig(Request $request)
    {
        //step_01 获取头像
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");

        $arr_head = $this->bigServiec->findhaibao_config($uniacid, $themeid);
        dump($arr_head);
    }

    //findhaibao_config_t
    public function findhaibao_config_t(Request $request)
    {
        //step_01 获取头像
        $themeid = $request->get("themeid");

        $arr_head = $this->bigServiec->findhaibao_config_t($themeid);
        dump($arr_head);
    }

    //根据平台id; uniacid 和 themeid 查询所有员工列表
    public function the_worklist(Request $request)
    {
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");

        $arr = $this->bigServiec->the_worklist($uniacid, $themeid);
        return json($arr);
    }

    //post
    public function edit_workone_by_openid(Request $request)
    {
        $og = $request->post();
        Log::write('edit_work_by_openid 入参' . json_encode($og), 'INFO');
        //Log::record('访问了someAction方法', 'info');
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $openid = $og['openid'];
        $identity = $og['identity'];
        $status = $og['status'];
        $arr = $this->bigServiec->edit_work_by_openid($uniacid, $themeid, $openid, $identity, $status);
        return json($arr);
    }

    //todo
    public function edit_workers_byopenid(Request $request)
    {
        $og = $request->post();
        Log::write('edit_workers_byopenid 入参' . json_encode($og), 'INFO');
//        $uniacid = $og['uniacid'];
//        $themeid = $og['themeid'];
//        $openid =  $og['openid'];
//        $identity = $og['identity'];
//        $status = $og['status'];
//        //第一次子对象是数组
//        $works = $og['works'];
//
//        $len = count($works);
        $arr = array();
//        for($i= 0 ;$i < $len;$i++){
//            //$works[$i]['openid'];
//            //$works[$i]['identity'];
//            $arr[$i] = $this->bigServiec->edit_work_by_openid($uniacid,$themeid,$openid,$identity,$status);
//        }

        return json($arr);
    }
    //todo
    //批量删除员工
    //del_workers_byopenid
    public function del_workers_byopenid(Request $request)
    {
        $og = $request->post();
        $uniacid = $og['uniacid'];
        $themeid = $og['themeid'];
        $openid = $og['openid'];
        $identity = $og['identity'];
        $status = $og['status'];
        //第一次子对象是数组
        $works = $og['works'];
    }

    //secondpayrefund
    public function gettidby39like(Request $request)
    {
        //step_01 获取头像
        $s39like = $request->get("s39likekey");

        $arr = $this->bigServiec->gettidby39like($s39like);
        //$needt = $arr
        $o = $arr['sqldata'];
        $len = count($arr['sqldata']);
        $arr2 = array();
        if ($len > 0) {
            $item = $o[0];
            //var_dump($item);
            $arr2['key'] = $item['tid'];
        } else {
            $arr2['key'] = "";
        }
        return $arr2;

    }

    //Detailid 同理  6Oid 其实是record 有多条
    public function getOrderByOid(Request $request)
    {
        //step_01 获取头像
        $s39like = $request->get("orderid");

        $arr = $this->bigServiec->gettidby39like($s39like);
        //$needt = $arr
        $o = $arr['sqldata'];

        return json_encode($o);
//        if(count($o)>0){
//            return json_encode($o[0]);
//
//        }
//        return '无数据';

    }

    public function getjyByOid(Request $request)
    {
        //step_01 获取头像
        $s39like = $request->get("orderid");

        $arr = $this->bigServiec->gettidby39like($s39like);
        //$needt = $arr
        $o = $arr['sqldata'];

        return json_encode($o);
//        if(count($o)>0){
//            return json_encode($o[0]);
//
//        }
//        return '无数据';

    }


    public function oneordercx(Request $request)
    {
        $detailid = $request->get("detailid");
        $arr = $this->bigServiec->gettidby39like($detailid);
        return json_encode($arr);
    }


    public function getpaychoice(Request $request)
    {
        $pid = $request->get("pid");
        $api_url = "https://gateway.cmxz.com.cn/oa/api/platform/info";

        $params_a = [
            'pid' => $pid
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');


        $jsonObject = json_decode($http_data);
        //$name = $jsonObject->data->pay_method->name;
        $r['status'] = $jsonObject->data->pay_method->status;
        $r['name'] = $jsonObject->data->pay_method->name;
        return json_encode($r);
    }

    public function getpaychoicebypid($pid)
    {
        $api_url = "https://gateway.cmxz.com.cn/oa/api/platform/info";

        $params_a = [
            'pid' => $pid
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');

        $jsonObject = json_decode($http_data);
        //$r['status'] = $jsonObject->data->pay_method->status;

        return $jsonObject->data->pay_method->status;
    }


    function curl_request2($url, $method = 'post', $params, $header, $type = 'http')
    {
        /**
         * 初始化curl，返回资源
         */
        $curl = curl_init($url);
        /**
         * 默认是get请求，如果是post/put请求，设置请求方式和请求参数
         */


        if (strtoupper($method) == 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params); // 这里传入的是 JSON 字符串
        } elseif (strtoupper($method) == 'GET') {
            // 对于 GET 请求，将参数拼接到 URL 后面
            if (!empty($params)) {
                $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
            }
        }

        if (strtoupper($method) == 'PUT') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if (!empty($params)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            }
        }


        /**
         * 设置header头部传参
         */
        if (!empty($header)) {

            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        /**
         * 如果是HTTPS协议，禁止从服务器验证本地证书
         */
        if (strtoupper($type) == 'HTTPS') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        /**
         * 超时设置，单位毫秒
         */
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 20000);
        /**
         * 发送请求，返回结果
         */
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        /**
         * 不验证ssl
         */
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        /**
         * 选择地址
         * curl_setopt($curl,CURLOPT_URL,$url);
         */
        $res = curl_exec($curl);

        if ($res === false) {
            $error = curl_error($curl);
            curl_close($curl);
            // 抛出一个异常或返回错误信息
            throw new Exception("CURL Error: " . $error);
        }

        /**
         * 关闭请求
         */
        curl_close($curl);
        return $res;

    }

    //post phpabcoupons
    //todo 加额外参数，默认关闭 "no" "yes"   newflagbuy newflaginvite
    public function phpabcoupons(Request $request)
    {

        $og = $request->post();
        //Log::info("翻卡牌入参：" .json_encode($og));


        $pid = $og['pid'];
        $aid = $og['aid'];
        $openid = $og['openid'];

        //todo 调老的计算
        $newflagbuy = input('post.newflagbuy', "0"); // 第二个参数是默认值
        $newflaginvite = input('post.newflaginvite', "0"); // 第二个参数是默认值
        LOG::info("总-翻卡牌入参" . json_encode($og));
        if ($newflagbuy == 1 || $newflaginvite == 1) {
            LOG::info("新版-翻卡牌入参" . json_encode($og));
            $arr = $this->bigServiec->phpabcoupons_new($pid, $aid, $openid, $newflagbuy, $newflaginvite);
        } else {
            LOG::info("旧版-翻卡牌入参" . json_encode($og));
            $arr = $this->bigServiec->phpabcoupons($pid, $aid, $openid);
        }

        return json_encode($arr);
    }

    public function phpabc_buynum_new_c(Request $request)
    {
        $og = $request->post();
        $pid = $og['pid'];
        $aid = $og['aid'];
        $openid = $og['openid'];
        $arr['og'] = $og;
        $arr['phpabc_buynum_new_s'] = 'phpabc_buynum_new_s';
        $arr = $this->bigServiec->phpabc_buynum_new_s($pid, $aid, $openid);
        return json_encode($arr);
    }


    //测试 phpabc_invitenum_new_s
    public function phpabc_invitenum_new_c(Request $request)
    {
        $og = $request->post();
        $pid = $og['pid'];
        $aid = $og['aid'];
        $openid = $og['openid'];
        $arr['og'] = $og;
        $arr['phpabcoupons_notold'] = 'phpabcoupons_notold';
        $arr = $this->bigServiec->phpabc_invitenum_new_s($pid, $aid, $openid);
        return json_encode($arr);
    }


    //只有新学员才有奖励,老学员没奖励
    public function phpabcoupons_new(Request $request)
    {
        //只选新生

    }

    public function phpabcoupons_notold(Request $request)
    {
        //不含老

    }

    public function oafpcreate(Request $request)
    {
        $url = 'https://oa.cmzg.vip/api/invoice/create/';
        $og = $request->post();
        //--------
        $order_name = $og['order_name'];
        $pid = $og['pid'];
        $aid = $og['aid'];
        $oid = $og['oid'];
        $uid = $og['uid'];
        $uid_avatar = $og['uid_avatar'];
        $uid_nickname = $og['uid_nickname'];
        $invoice_amount = $og['invoice_amount'];
        $invoice_type = $og['invoice_type'];
        $invoice_title_type = $og['invoice_title_type'];
        $invoice_title = $og['invoice_title'];
        $tax_number = $og['tax_number'];
        $billing_bank = $og['billing_bank'];
        $bank_account = $og['bank_account'];
        $company_phone = $og['company_phone'];
        $company_address = $og['company_address'];
        $mobile_phone = $og['mobile_phone'];
        $email = $og['email'];

        $params_a = [
            'order_name' => $order_name,
            'pid' => $pid,
            'aid' => $aid,
            'oid' => $oid,
            'uid' => $uid,
            'uid_avatar' => $uid_avatar,
            'uid_nickname' => $uid_nickname,
            'invoice_amount' => $invoice_amount,
            'invoice_type' => $invoice_type,
            'invoice_title_type' => $invoice_title_type,
            'invoice_title' => $invoice_title,
            'tax_number' => $tax_number,
            'billing_bank' => $billing_bank,
            'bank_account' => $bank_account,
            'company_phone' => $company_phone,
            'company_address' => $company_address,
            'mobile_phone' => $mobile_phone,
            'email' => $email
        ];


        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
        return $http_data;
    }


    public function useractivity(Request $request)
    {
        $phone = $request->get("phone");

        return ($this->my_curl($phone));
    }

    function my_curl($phoneNumber)
    {
        // 定义接口 URL，使用传入的电话号码作为动态部分
        $url = "https://gateway.cmxz.com.cn/wq/api/v1/user/activity/{$phoneNumber}/?format=json";

        // 初始化 cURL
        $ch = curl_init();

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url); // 设置请求的 URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应结果以字符串形式返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过 SSL 证书验证（仅用于测试环境）
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过主机验证（仅用于测试环境）

        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);

        //额外加的
        if ($response === false) {
            echo 1;
            $error = curl_error($ch);
            curl_close($ch);
            // 抛出一个异常或返回错误信息
            throw new Exception("CURL Error: " . $error);
        } else {

            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//            echo "响应码".$httpCode;
//            echo "<br>";
//            echo $response;
        }

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            echo 'cURL 错误: ' . curl_error($ch);
            curl_close($ch);
            return false;
        }

        // 获取 HTTP 响应码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭 cURL 资源
        curl_close($ch);

        // 判断 HTTP 状态码是否为 200（成功）
        if ($httpCode == 200) {
            // 解析 JSON 数据
            return $response;
            $data = json_decode($response, true);
            //不解开 因为 解开了 就是数组了

            // 检查 JSON 解析是否成功
            if (json_last_error() === JSON_ERROR_NONE) {
                return $data; // 返回解析后的数据
            } else {
                echo 'JSON 解析错误: ' . json_last_error_msg();
                return false;
            }
        } else {
            echo 'HTTP 请求失败，状态码: ' . $httpCode;
            return false;
        }
    }

    //newordertooa(//订单号)

    //oneorder
    public function pconeorder(Request $request)
    {
        $og = $request->post();
        $keyword = $og['keyword'];
        //怎么判断 关键字是手机号 如果是手机号就是 sql等于
        $bgtime = $og['bgtime'];
        $endtime = $og['endtime'];
        $pid = $og['pid'];
        $aid = $og['aid'];
    }

    //pcmoreorders 用in
    public function pcmoreorders(Request $request)
    {
        $og = $request->post();
        $keyword = $og['keyword'];
        //怎么判断 关键字是手机号 如果是手机号就是 sql等于
        $pids = $og['pids'];  //json 数组怎么传进来
        $aids = $og['aids'];  //json 数组怎么传进来
        $bgtime = $og['bgtime'];
        $endtime = $og['endtime'];


    }

    //关于订单导出,
    public function orderdaopage()
    {

    }


    //再看把 比如本页是10条,选择了3条
    public function orderdaochose()
    {

    }

    //doNewOrderToOA(){}
    //
    //陈鑫给的 22025042709565345719013711625 去头后 能通过订单号ordersn（u 是空的）
    public function findOrderBytid2(Request $request)
    {
        $tid2 = $request->get("tid2");
        $arr = $this->bigServiec->findOrderBytid2($tid2);
        return json_encode($arr);
    }

    //findOrderBytid2_v2  作用不光返回order的detail_id,同时会拿到record对象的更多数据，例如 pid  团长  noid 当前团
    public function findOrderBytid2_v2(Request $request)
    {
        $arr = $request->param();
        Log::info("findOrderBytid2_v2".json_encode($arr));
        $tid2 = $request->get("tid2");
        $arr1 = $this->bigServiec->findOrderBytid2($tid2);
        $detailid = $arr1['detailid'];
        //return json_encode($arr1);
        $arr2 = $this->bigServiec->findRecordByxx($detailid);
        //  更新PC逻辑 开始
        $noid = $arr2['noid'];  //
        //只有团员订单；才影响别人
        //$pid = $arr2['pid'];
        if($detailid != $noid){
            $arr_noid = $this->bigServiec->findRecordByNoid($noid); //一组订单
            $this->updateOnidRecord($arr_noid);
        }



        //  更新PC逻辑 结束

        return json_encode($arr2);
    }

    public function pay_tuan_fix($arr2){

        //$detailid 就是ims_water_salegroup3_record 的id; 就是微擎页面的"订单"目前是5开头，
        //微信支付transssss表的id是8开头了。899323 交易id 没什么用

        //第一步查当前的支付是开团还是拼团
        //如果是开团订单（java已经更新了)

        //如果是拼团订单 说明还需要修改相关订单


    }

    //detailid = 606905  按道理能找到 596121 订单对象  ty
    public function t_tyorderlist(Request $request){
        $detailid = $request->get('detailid');
        $arr2 = $this->bigServiec->findRecordByxx($detailid);
        //取出 pid
        $noid = $arr2['noid'];
        //找所有 pid是x1的所有订单（包含团长订单） 例如多个订单对象。
        //找出所有团员订单
        //所有这一批订单也行
        //过滤字段。订单id + 入参体 例如已有团人数，是否满团(拼团中)提交给夏天的接口

        //找出同组订单,两个最新的订单
        $arr_noid = $this->bigServiec->findRecordByNoid($noid);
        return $this->updateOnidRecord($arr_noid);
        //return json_encode($arr_noid);
        //注意，可以有返回，但是外面不拿也没事
    }

    public function updateOnidRecord($arr_noid){
        $len = count($arr_noid);
        $xia = "https://gateway.cmxz.com.cn/oa/api/new/order/";
        $r = '';
        for ($i=0;$i<$len;$i++){
            $noid_record = $arr_noid[$i];
            $nid = "1".$noid_record['id'];
            $params_a = [
                'nid' => $nid,
                'status_pay' =>  $noid_record['paystate'],
                //'uniac_id' =>  $noid_record['uniacid'],
                //'ntheme_id' => "1" . $noid_record['themeid'],
                'num' => $noid_record['num'],
                'need_num' => $noid_record['neednum'],
                'has_num' => $noid_record['hasnum'],
                "status_finish" => $noid_record['isfinish'],
            ];
            $header = ['Content-Type: application/json'];
            $params_a = json_encode($params_a);
            //return $params_a;
            $http_data = $this->curl_request2($xia, $method = 'put', $params_a, $header, $type = 'https');
            $r.=$http_data;
        }

        return $r;

    }


    public function t_fixneworder(Request $request){
        //准备

    }

    public function fixneworder($arr){
        //$arr 是数组;因为有多个对象
        //夏天的更新对象接口
    }

    public function tyorderlist(){

    }

    // getapp
    public function getapp(Request $request)
    {

        $arr = $this->bigServiec->getapp();
        return json_encode($arr);
    }

    //wechats
    public function getwechats(Request $request)
    {
        $arr = $this->bigServiec->getwechats();
        return json_encode($arr);
    }


    //getappbypid
    public function getappbypid(Request $request)
    {
        $arr = $request->param();
        Log::info("getappbypid".json_encode($arr));
        $pid = $request->get("pid");
        $arr = $this->bigServiec->getappbypid($pid);
        return json_encode($arr);
    }

    public function findappbypid(Request $request)
    {
        $pid = $request->get("pid");
        $arr1 = $this->bigServiec->getappbypid($pid);
        $arr2 = $arr1['sqldata'];
        $len2 = count($arr2);

        $r = [];
        if ($len2 > 0) {
            $r['has'] = 'yes';
            $r['key'] = $arr2[0]['key'];
            $r['secret'] = $arr2[0]['secret'];

        } else {
            $r['has'] = 'no';
        }
        return json_encode($r);

    }

//    public function creatNewOrder(Request $request){
//        $tid2 = $request->get("tid2");
//        $arr = $this->bigServiec->findOrderBytid2($tid2);
//
//        return json_encode($arr);
//    }

    public function findRecordByxx(Request $request)
    {
        $xx = $request->get("xx");
        $arr = $this->bigServiec->findRecordByxx($xx);
        return json_encode($arr);

    }

    public function findRecordByOrderid(Request $request)
    {
        $orderid = $request->get("orderid");
        $arr = $this->bigServiec->findRecordByxx($orderid);
        return json_encode($arr);

    }

    //todo
    public function getneworder_v2(Request $request)
    {

    }

    //getneworder  拼团，小程序cj 凭什么是拼团
    public function getneworder(Request $request)
    {
        return $this->getneworder_wnform($request);
    }

    public function getneworder_test(Request $request)
    {

        Log::info("getneworder_test: " . json_encode($request->param(), JSON_UNESCAPED_UNICODE));
        return $this->getneworder_wnform($request);
    }

    public function findobj_forfix(Request $request){
        Log::info("findobj_forfix: " . json_encode($request->param(), JSON_UNESCAPED_UNICODE));

        $oid =$request->get("oid");
        $arr1 = $this->bigServiec->findobj_forfix($oid);
        return json_encode($arr1);
    }

    public function getneworder_fix(Request $request)
    {
        Log::info("getneworder_fix1: " . json_encode($request->param(), JSON_UNESCAPED_UNICODE));
        //$request->setParam(["name" => "罗"]);
        //todo 去DB捞一个 tid2 的 list

        //根据pid 53  aid 12615 查所有订单
        //  ims_water_salegroup3_order
        $arr1 = $this->bigServiec->find_orders_bypidaid(53,12615);
        $len = count($arr1);
        //return $len;
        //var_dump($arr1);

//        try {
//            sleep(0.3);
//            $this->getneworder_wnform($request);
//            return 'abc';
//        } catch (\Exception $e) {
//            return $e;
//        }


        for($i=0;$i<$len;$i++){
            //echo  $arr1[$i]['tid'];
            $request->setParam(["tid2" => $arr1[$i]['tid']]);


            //多次调另一个控制器
            //sleep(0.3);  错误。我记得不能小数
            sleep(1);
            try {
                //sleep(0.5);
                $this->getneworder_wnform($request);
                echo "abc";
            } catch (\Exception $e) {
              echo "xyz";
            }
            //$this->getneworder_wnform($request);
            echo  json_encode($request->param(), JSON_UNESCAPED_UNICODE);
        }
        //return "ok";
    }


    public function getneworder_wnform(Request $request)
    {
        $wnformflag = $request->get("wnformflag"); //222
        $bigjson = $request->get("bigjson"); //字符串
        $inbig = $request->get("inbig");
        $bossphone = $request->get("bossphone");

        $test = $request->get("test"); //222
        $okfee = $request->get('okfree');
        if ($okfee == 'yes') {
            $shortorderid = $request->get('shortorderid');
            $arr1 = $this->bigServiec->findOrderByShortid($shortorderid);
            //return json_encode($arr1);
            //根据短的订单号来查订单
            $dytid2 = '3'; //丢了 用sn合适不
            $detailid = $shortorderid;
        } else {
            $tid23 = $request->get("tid2"); //222
            $dytid2 = $request->get("tid2"); //222
            $tid23 = substr($tid23, 1);
            $arr1 = $this->bigServiec->findOrderBytid2($tid23);
            $detailid = $arr1['detailid'];
        }

        $uniacid = $arr1['uniacid'];
        $themeid = $arr1['themeid'];
        //todo ok
        try {
            $arr_theme = $this->bigServiec->findThemebyid($themeid);
            $theme_name = $arr_theme['title'];
        } catch (Exception $e) {
            // 处理其他可能的异常
            error_log("Unexpected error calculating profit for themeid {$themeid}: " . $e->getMessage());
            return 'short err and find theme null';
        }


        $avatar = $arr1['avatar'];
        $username = $arr1['username'];
        $nickname = $arr1['nickname'];
        $mobile = $arr1['mobile'];

        //$status_pay = $arr1['paystate'];   //夏天想当然。和柱哥word文档不一样
        //id 就是 detailid
        $arr2 = $this->bigServiec->findRecordByxx($detailid);


        if ($test == 'yess') {
            //return  json_encode($arr2);
        }

        $status_pay = $arr2['status']; //改成这个


        if ($test == 'yess') {
            return "duan2222";
        }

        $billcode = $arr2['billcode'];
        $openid = $arr2['openid'];
        $fee = $arr2['fee'];
        $option = $arr2['option'];
        $option2 = $arr2['option2'];
        $option3 = $arr2['option3'];
        $option4 = $arr2['option4'];
        $option5 = $arr2['option5'];
        $note = $arr2['address'];
        $note2 = $arr2['datetime'];
        $f_openid = $arr2['fopenid'];
        $status_refund = $arr2['isrefund'];
        $refund_fee = $arr2['refund_fee'];
        $add_time = $arr2['addtime'];
        $add_time = date("Y-m-d H:i:s", $add_time);
        $pay_time = $arr2['paytime'];
        $pay_time = date("Y-m-d H:i:s", $pay_time);
        $status_type = $arr2['type'];


        $pid = $arr2['pid']; // 所属团长
        $noid = $arr2['noid'];
        $status_finish = $arr2['isfinish'];  //0 拼团中 1已成团
        $num = $arr2['num'];
        $need_num = $arr2['neednum'];
        $has_num = $arr2['hasnum'];
        $remark = $arr2['remark'];
        $source_openid = $arr2['sourceid'];
        $verify_time = $arr2['verifytime'];
        $verify_time = date("Y-m-d H:i:s", $verify_time);

        $verify_openid = $arr2['verifyopenid'];
        $birthday = $arr2['birthday'];
        $gender = $arr2['gender'];
        if ($gender == '男生') {
            $gender = 1;
        } else {
            $gender = 2;
        }
        $groups = $arr2['groups'];
        $way = $arr2['way'];


        //如果是费自收款订单
        $r = $this->getpaychoicebypid($uniacid);

        //to togetfrom xialu
        $mch_id = '';
        $api_v3_key = "";
        $private_key = "";
        $apiclient_cert = "";
        $mch_serial_number = "";
        $pubkey_id = "";
        $pubkey_pem = "";

        $paymsg = [];
        if (1 == $r) {
            $lg = "no"; //自收款 不做处理 原来不做处理，现在我去小卢的接口查支付信息
            //todo1 查活动是属于哪个老板
            //https://back.screen.cmxz.com.cn/index.php/phone3?aid=11540
            $bossphone = $this->findboss($themeid);
            if ($bossphone == "") {
                Log::info("查boss没有查到：" . $themeid);
            } else {
                //findpaymsg($bossphone)
                $r = $this->findpaymsg($bossphone);
                if (empty($r)) {
                    //echo '数组为空';
                    Log::info("数组为空：" . $themeid);
                } else {
                    Log::info("数组不空：" . json_encode($r));
                    //echo '数组不为空';
                    //todo 组装支付数据
                    $mch_id = $r['mchId'];
                    $api_v3_key = $r['apiV3kEY'];
                    $private_key = $r['privateKey'];
                    $apiclient_cert = $r['apiclientCert'];
                    $mch_serial_number = $r['mchSerialNumber'];
                    $pubkey_id = $r['pubkeyId'];
                    $pubkey_pem = $r['pubkeyPem'];

                }
            }

        } else {
            $lg = "yes"; //老业务。 每日 秒 代理
//            $arr1 = $this->bigServiec->findpaymsgbypid($themeid);
//
//            if($arr1->isEmpty()) {
//                //return "444444";
//            }else{
//                $data = $arr1[0];
//                $setting_ss = $data['settings'];
//                $setting = unserialize($setting_ss);
//
//                $mch_id= $setting['mchid'];
//                $api_v3_key=$setting['apikey'];
//                $mch_serial_number=$setting['mch_serial_no'];
//                $private_key=$setting['apiclient_key'];
//                $apiclient_cert=$setting['apiclient_cert'];
//            }
        }
        //todo 1
        $f_openid_name = '直推人姓名';
        //todo 2
        $source_openid_name = "溯源人姓名";
        try{
            if($f_openid !=""){
                $obj = $this->find_f_name($uniacid,$themeid,$f_openid);
                $itme = $obj->first();
                $f_openid_name = $itme['nickname']; //刘柱
            }

            if($source_openid !=""){
                $obj = $this->find_f_name($uniacid,$themeid,$source_openid);
                $itme = $obj->first();
                $source_openid_name = $itme['nickname']; //刘柱
            }

        }catch (\Exception $e){
            Log::info("找昵称出错".$uniacid.'-'.$themeid.'-'.$source_openid);
        }


        //$source_openid_name = $this->find_s_name($source_openid);

        $url = 'https://gateway.cmxz.com.cn/oa/api/new/order/';
        $params_a = [
            'cxtid2' => $request->get("tid2"),
            'lg' => $lg,
            'nid' => "1" . $detailid,
            'dytid2' => $dytid2,
            'uniac_id' => $uniacid,
            'ntheme_id' => "1" . $themeid,
            'theme_name' => $theme_name,
            "bill_code" => $billcode,
            "nickname" => $nickname,
            "avatar" => $avatar,
            "username" => $username,
            "mobile" => $mobile,
            "openid" => $openid,
            "fee" => $fee,
            "option" => $option,
            "option2" => $option2,
            "option3" => $option3,
            "option4" => $option4,
            "option5" => $option5,
            "note" => $note,
            "note2" => $note2,
            "f_openid" => $f_openid,
            "f_openid_name" => $f_openid_name,
            "status_refund" => $status_refund,
            "refund_fee" => $refund_fee,
            "status_pay" => $status_pay,

            "add_time" => $add_time,
            "pay_time" => $pay_time,

            "status_type" => $status_type, //身份
            "pid" => $pid,
            "noid" => $noid,
            "status_finish" => $status_finish,

            "num" => $num,
            "need_num" => $need_num,
            "has_num" => $has_num,

            "remark" => $remark,
            "source_openid" => $source_openid,
            "source_openid_name" => $source_openid_name,

            "verify_time" => $verify_time,
            "verify_openid" => $verify_openid,
            //"birthday" => "1979-01-01",
            "birthday" => $birthday,
            "gender" => $gender,
            "groups" => $groups,
            "way" => $way,


            "cmzg_refund_status" => 0,
            //"cmzg_refund_time" => "1979-01-01 00:00:00",
            "cmzg_refund_time" => "",


//            'api_v3_key'=>$api_v3_key,
//            'mch_serial_number'=>$mch_serial_number,
//            'private_key'=>$private_key,
//            'apiclient_cert'=>$apiclient_cert


            "mch_id" => $mch_id,
            "api_v3_key" => $api_v3_key,
            "private_key" => $private_key,
            "apiclient_cert" => $apiclient_cert,
            "mch_serial_number" => $mch_serial_number,
            "pubkey_id" => $pubkey_id,
            "pubkey_pem" => $pubkey_pem,

            "bossphone"=>$bossphone
        ];

        if ("yes" == $wnformflag) {
            Log::info("夏天新订单V2：" . $detailid);
            //合并一个数组
            // 合并一个数组（优化版）
            //$arrwnform1 = wnformopt1
            //$arrwnform2 = wnformopt2

            $arrwnform = [];
//            for ($i = 1; $i <= 20; $i++) {
//                $key = 'wnformopt' . $i;
//                $arrwnform[$key] = $request->get($key);
//            }

//            "collect_name_key":"客户姓名",
//    "collect_name_value":"张三",
//    "collect_phone_key":"客户手机号",
//    "collect_phone_value":"17761739482",
//    "collect_sf_key": "客户身份",
//    "collect_sf_value": "新生,老生",
//    "collect_sf_select": "老生",
//    "collect_json"

//            $arrwnform['collect_name_key'] = "t客户姓名";
//            $arrwnform['collect_name_value'] = "张三";
//
//            $arrwnform['collect_phone_key'] = "t客户手机号";
//            $arrwnform['collect_phone_value'] = "17761739482";
//
//            $arrwnform['collect_sf_key'] = "客户身份";
//            $arrwnform['collect_sf_value'] = "新生,老生";
//            $arrwnform['collect_sf_select'] = "老生";

            $fakejson = '[
    {"logo":"x",   "type":"one","title":"昵称", "text":"爱新觉罗"   },
    {"logo":"x",   "type":"sc","least":0,"most":10,  "ck":"no" ,"title":"爱好","showlabels":["语","数","外"] ,"vv":["语","数"] },
    {"logo":"x",   "type":"sc","least":0,"most":11,  "ck":"no" ,"title":"课程1","showlabels":["语1","数1","外1"]   }
]';
            if ($inbig == 'no') {
                $arrwnform['collect_json'] = $fakejson;
            } else {
                $arrwnform['collect_json'] = $bigjson;
            }


            //合并数组
            $params_a = array_merge($params_a, $arrwnform);
        }

        $header = ['Content-Type: application/json'];
        if ($test == 'yesyes') {
            $params_a['nid'] = "3".mt_rand(10000, 99999);
        }
        $params_a = json_encode($params_a);
        //加一个日志
        Log::info("夏天新订单V1：" . $params_a . "-" . $detailid);
        if ($test == 'yes') {
            return $params_a;
        }

        if ($test == 'yesyes') {
            $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
            $xr['in'] = $params_a;
            $jsonData = json_decode($http_data, true);
            $xr['out']=$jsonData;
            return json_encode($xr);
        }


        $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');

        // 尝试解码 JSON
        $jsonData = json_decode($http_data, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            // 是有效的 JSON
//            Log::info('cURL Response (JSON)', [
//                'url' => $url,
//                'response_type' => 'json',
//                'data' => $jsonData, // ThinkPHP Log 通常能处理数组
//                // 注意：如果 $jsonData 非常大，依然要考虑截取或只记录关键字段
//            ]);

            Log::info('夏天返回v3' . $http_data . '入参' . $detailid);
        } else {
            // 不是 JSON，当作普通文本/HTML 处理
            $length = strlen($http_data);
            $prefix = mb_strcut($http_data, 0, 150, 'UTF-8');
            Log::info('cURL Response (Non-JSON)', [
                'url' => $url,
                'response_type' => 'text/html or other',
                'response_length' => $length,
                'response_start' => $prefix . '...',
                'content_type' => curl_getinfo($url, CURLINFO_CONTENT_TYPE),
            ]);
        }

        return $http_data;

    }


    public function testfindboss(Request $request)
    {
        $aid = $request->get("aid");
        $phone = $this->findboss($aid);
        if ($phone == "") {
            return "手机号为空";
        }
        return $phone;
    }

    public function testfindpaymsg(Request $request)
    {
        $phone = $request->get("phone");
        $r = $this->findpaymsg($phone);
        print_r($r);
        if (empty($r)) {
            //echo '数组为空';
        } else {
            //echo '数组不为空';

        }
    }

    public function findboss($aid)
    {

        $arr1 = $this->bigServiec->findphonebyaid_1($aid);
        if (count($arr1) > 0) {
            $row = $arr1[0];   //一条 活动数据
            $uid = $row['uid'];
            $arr2 = $this->bigServiec->findphonebyaid_2($uid);
            if (count($arr2) > 0) {
                return $arr2[0]['username'];
            }
        }
        return "";
    }

    public function xtfindbossphone(Request $request)
    {
        //专门写个夏天用的
        $aid = $request->get('aid');
        $arr['bossphone'] = $this->findboss($aid);
        return json_encode($arr);
    }

    public function xtfindpaymsg(Request $request)
    {
        $bossphone = $request->get('bossphone');
        $r = $this->findpaymsg($bossphone);
        $r['bossphone'] = $bossphone;
        return json_encode($r);
    }


    public function findpaymsg($bossphone)
    {
        $params_a = [
            'bossphone' => $bossphone
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
//        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');

        $url = "https://back.smartshopkeeper.com/admin-api/cmzgMerchantPayConfig/queryBossFzConfig";
        $http_data = $this->curl_request2($url, $method = 'post', $params, $header, $type = "https");
        $jsonObject = json_decode($http_data);
        $data = $jsonObject->data;

        $mchId = $data->mchId;
        $apiV3Key = $data->apiV3Key;
        $privateKey = $data->privateKey;
        $apiclientCert = $data->apiclientCert;
        $mchSerialNumber = $data->mchSerialNumber;
        $pubkeyId = $data->pubkeyId;
        $pubkeyPem = $data->pubkeyPem;
        $payMode = $data->payMode;

        $r['mchId'] = $mchId;
        $r['apiV3kEY'] = $apiV3Key;
        $r['privateKey'] = $privateKey;
        $r['apiclientCert'] = $apiclientCert;
        $r['mchSerialNumber'] = $mchSerialNumber;
        $r['pubkeyId'] = $pubkeyId;
        $r['pubkeyPem'] = $pubkeyPem;
        $r['payMode'] = $payMode;
        return $r;
    }


    //抢购的临时写这个项目。


    //findpaymsgbypid
    public function findpaymsgbypid(Request $request)
    {

        $pid = $request->get("pid"); //222

        $arr1 = $this->bigServiec->findpaymsgbypid($pid);

        if (!empty($arr1)) {
            $data = $arr1[0];
            $setting_ss = $data['settings'];
            $setting = unserialize($setting_ss);

            return json_encode($setting);
        } else {
            return 'error';
        }
    }

    public function findaidsbypid(Request $request)
    {
        $pid = $request->get("pid"); //222
        $arr1 = $this->bigServiec->findaidsbypid($pid);
        return json_encode($arr1);
    }

    //注意不是mppay时调
    //lg备注 ：只有 （秒到账 和 每日提现的订单）老业务 才需要这个接口 也就是 paychoice = 1 【自收款】时千万别调 浪费
    public function findwqdifforder(Request $request)
    {
        $dytid2 = $request->get("tid2");
        $tid2 = substr($dytid2, 1);
        $arr1 = $this->bigServiec->findOrderBytid2($tid2);
        //获取detailid
        $detailid = $arr1['detailid'];
        $arr2 = $this->bigServiec->findRecordByxx($detailid);
        $status_pay = $arr2['status']; //改成这个
        $params_a = [
            'nid' => "1" . $detailid,
            "status_pay" => $status_pay,
        ];
        $header = ['Content-Type: application/json'];
        $params_a = json_encode($params_a);
        $header = ['Content-Type: application/json'];
        $xia_url = "https://gateway.cmxz.com.cn/oa/api/new/order/";
        $http_data = $this->curl_request2($xia_url, $method = 'put', $params_a, $header, $type = 'https');
        return $params_a;
    }

    public function samecopy(Request $request)
    {
        //  http://gateway.cmxz.com.cn/wq/api/v1/user/activity/18320475247/  前端好像访问过了
        $pid = $request->get("pid"); //53
        $aid = $request->get("aid"); //2323
        $phone = $request->get("phone");
        $password = $request->get("password");
        $uid = $request->get("uid");
        $tcode = $request->get("tcode");
        $cxcode10 = $request->get("tcode");
        $encryptedString = md5($phone . $password);
//        if($encryptedString !== $cxcode10){
//            return "服务接口无数据";
//        }
        //return json_encode($arr1);
        //拼团的 salegroup3
        $url = " https://cm.cmzg.vip/app/index.php?i=" . $pid;
        $url .= "&c=entry&do=api_copy_theme&m=water_salegroup3&themeid=" . $aid;
        $url .= "&uid=" . $uid;
        $header = ['Content-Type: application/json'];
        //$r = $this->curl_request2($url,'get',null,$header,'https');
        $http_data = $this->curl_request2($url, $method = 'get', $params = [], $header = [], $type = 'https');
        return 'ok';
    }

    //diffcopy() 不同平台和活动的拷贝。 目的是想做不同类型
    public function diffcopy(Request $request)
    {
        $xiapids = '';

        // findcasebypid
        $pid = 1;

        $aid = $this->findcasebypid($pid);
        $uid = 1;
        return $aid;
        //todo diffcopy
        //return json_encode($aid);
    }

    //findNpidbyoa() 查找 需要跨平台拷贝活动的pid  夏天提供的接口,拼团和抢购 都有。前端传$pid() 内服方法写一个。给陈鑫的是两个
    public function findNpidbyoa($pay, $plat)
    {
        return $pay . $plat;
    }

    public function findcasebypid($pid)
    {
        $arr1 = $this->bigServiec->findcasebypid($pid);
        if (count($arr1) > 0) {
            $r = $arr1[0];  //随便取一个
            return $r['id'];
        } else {
            return '没用数据';
        }
    }


    //给谁调用的，哪个项目 陈鑫
    //todo 新版PC 同步订单
    // 本来想做批量更新的  因为夏天的更新 接口是单个。目前也只能单个了
    // 入参是$nid新版PC 所以不用拼接
    public function synorderbynid($nid, $test = 'no')
    {
        //todo1 陈鑫新版订单id
        $page_detailid = $nid;
        $db_detailid = substr($page_detailid, 1);

        //togo
    }

    //findpidaidforfengbyphone
    public function findpidaidforfengbyphone($phone)
    {
        $arr1 = $this->bigServiec->findpidaidforfengbyphone_1($phone);

        //return json_encode($arr1);
        if (count($arr1) > 0) {
            $row = $arr1[0];  //随便取一个
            $uid = $row['uid'];
            $arr1 = $this->bigServiec->findpidaidforfengbyphone_2($uid);
            $r['pid'] = $arr1[0]['uniacid'];
            $r['aid'] = $arr1[0]['id'];
            $r['db'] = $arr1;
            return json_encode($r);
        } else {
            return '没用数据';
        }
    }

    public function findpidaidforfengbyphoneaid($phone, $aid)
    {
        $arr1 = $this->bigServiec->findpidaidforfengbyphone_1($phone);
        $r['db1'] = $arr1;
        //return json_encode($arr1);
        if (count($arr1) > 0) {
            $row = $arr1[0];  //随便取一个
            $uid = $row['uid'];
            $arr2 = $this->bigServiec->findpidaidforfengbyphone_3($uid, $aid);
            $r['pid'] = $arr2[0]['uniacid'];
            $r['aid'] = $arr2[0]['id'];
            $r['db'] = $arr2;

            $r['has'] = 'yes';
            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }
    }

    public function findpidaidforfengbyaid($aid)
    {
        $arr1 = $this->bigServiec->findpidaidforfengbyaid($aid);
        return json_encode($arr1);
        //return json_encode($arr1);
//        if(count($arr1) > 0 ){
//            $row = $arr1[0];  //随便取一个
//            $uid =  $row['uid'];
//            $arr2 = $this->bigServiec->findpidaidforfengbyphone_3($uid,$aid);
//            $r['pid']=$arr2[0]['uniacid'];
//            $r['aid']=$arr2[0]['id'];
//            $r['db']=$arr2;
//            $r['has']='yes';
//            return json_encode($r);
//        }else{
//            $r['has']='no';
//            return json_encode($r);
//        }


    }


    //根据 活动来查  $phone
    public function findphonebyaid(Request $request)
    {
        $aid = $request->get('aid');
        $arr1 = $this->bigServiec->findphonebyaid_1($aid);
        if (count($arr1) > 0) {
            $row = $arr1[0];   //一条 活动数据
            $uid = $row['uid'];
            $arr2 = $this->bigServiec->findphonebyaid_2($uid);
            if (count($arr2) > 0) {
                //$r['db']=$arr1;
                $r['phone'] = $arr2[0]['username'];
                $r['has'] = 'yes';
                return json_encode($r);
            }
            $r['has'] = 'no';
            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }
    }

    //phone3的3 是指第三次尝试 写个接口 给 secondpay 项目使用。
    public function phone3($aid)
    {
        $arr1 = $this->bigServiec->findphonebyaid_1($aid);
        if (count($arr1) > 0) {
            $row = $arr1[0];   //一条 活动数据
            $uid = $row['uid'];
            $arr2 = $this->bigServiec->findphonebyaid_2($uid);
            if (count($arr2) > 0) {
                //$r['db']=$arr1;
                $r['phone'] = $arr2[0]['username'];
                $r['has'] = 'yes';
                return json_encode($r);
            }
            $r['has'] = 'no';
            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }

    }

    public function cstime($t)
    {
        //echo $t;
        sleep($t);
        return $t;
    }


    //todo 查用户
    public function findchouuser(Request $request)
    {
        //  $pid = $request->get('pid'); 平台下cj 的openid 和 jx的opneid 不一样但是 不同活动是一样的 所以入参是pid
        $pid = $request->get('pid');
        $arr = ["otRw95Sjm0t3zmYfFB_aL3KQgDmE", "otRw95Xn-Gcbj7x0ajFpba79uY8I", "otRw95T9Y1X6S4ybRD_iUr4h0uYs", "otRw95Xn-Gcbj7x0ajFpba79uY8I", "otRw95f0_n2XXsZpL-3KRACiIkIY", "otRw95f0_n2XXsZpL-3KRACiIkIY", "otRw95RiefBBqv4towbVLZ721G0k", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Xn-Gcbj7x0ajFpba79uY8I", "otRw95ZJaJFr1o6r2UID4nLTdWps", "otRw95Xn-Gcbj7x0ajFpba79uY8I", "otRw95Xn-Gcbj7x0ajFpba79uY8I", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Rrl53wBIJS9_wojx62d6gs", "otRw95Q82zmvqZpbEAJqePcomn9U"];
        $arr2 = $this->bigServiec->findchouuser(53, $arr);

        return json_encode($arr2);
    }

    //todo 代理商的活动 findaidsbyphone()
    public function findaidsbyphone(Request $request)
    {
        //step1  通过phone 找到uid
        $phone = $request->get('phone');
        $cpage = $request->get('cpage');
        $listrows = $request->get('rows');
        //通过phone找到老板记录. “记录” 中的uid
        $arr1 = $this->bigServiec->findpidaidforfengbyphone_1($phone);
        //return json_encode($arr1);
        //uid 所有uid 的them
        if (count($arr1) > 0) {
            $row = $arr1[0];  //随便取一个
            $uid = $row['uid'];
            $arr2 = $this->bigServiec->findaidsbyuid($uid, $cpage, $listrows);

            $r['has'] = 'yes';
            $r['user'] = $arr1;
            $r['db'] = $arr2;

            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }
    }

    public function oneworkergroupset(Request $request)
    {
        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $ids = $request->get("ids");
        $data = $request->get("data");

        $api_url = "https://cm.cmzg.vip/app/index.php?i=$pid&c=entry&do=api_update_worker&m=water_salegroup3&themeid=$aid&ids=$ids&data=$data";
        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');
        $jsonObject = json_decode($http_data);
        return $jsonObject;
    }

    //直接写INDEX 因为要利用curl好的工具
    public function oneworkergroupset_rush(Request $request)
    {
        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $ids = $request->get("ids");
        $data = $request->get("data");

        $api_url = "https://cm.cmzg.vip/app/index.php?i=$pid&c=entry&do=api_update_worker&m=water_groupbuy3&themeid=$aid&ids=$ids&data=$data";
        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');
        $jsonObject = json_decode($http_data);
        return $jsonObject;
    }


    //lglog001
    public function lglog001(Request $request)
    {

        $pid = $request->get("pid");
        //\think\Log::record('日志开启 能搜到嘛');
        //Logger::record("日志开启 能搜到嘛 ");
        //Log::info('这是一条日志信息');
        //
        Log::info("llog-$pid");
        return "OK";
    }

    //tx
    public function tx($purl)
    {
        Log::info("java-to-php3：" . $purl);
        //

        $original_url = urldecode($purl);
        Log::info("java-to-php3-de：" . $original_url);


        $http_data = $this->curl_request2($original_url, $method = 'get', $params = [], $header = [], $type = 'https');

        //$jsonObject = json_decode($http_data); 一个curl 不一定是json
        //Log::info("java-to-php2：{}-{}",$url,$http_data);
        return $http_data;
    }

    public function tx2(Request $request)
    {
        Log::info("tx2-java-to-php3：" . json_encode($request));

        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $table = $request->get("table");
        $recordid = $request->get("recordid");

        $flag = $request->get("flag");
        $liyou = $request->get("liyou");

        if ("ok" == $flag) {
            //  map.put("cmzgrefundstatus", "1");
            //todo 2025-10-23 如果是拼团的退款成功
            if("water_salegroup3" == $table){
                //如果是拼团的退款。
                //cur_order =
                $arr2 = $this->bigServiec->findRecordByxx($recordid);
                //  更新PC逻辑 开始
                $noid = $arr2['noid'];

                //if($recordid != $noid){
                    $arr_noid = $this->bigServiec->findRecordByNoid($noid); //一组订单
                    $this->updateOnidRecord($arr_noid);
                //}

                //  更新PC逻辑 结束

            }

            $aa = array(
                'cmzgrefundstatus' => "1",
            );
        } else {
            $aa = array(
                'cmzgrefundstatus' => "2",
                'cmzgrefundreject' => $liyou
            );
        }


//        // Step 1: 转成 JSON 字符串
        $json_str = json_encode($aa, JSON_UNESCAPED_UNICODE); // 不转中文为 Unicode
//        // Step 2: 模拟 JavaScript 的 encodeURIComponent
        $dataStr = $this->encodeURIComponent($json_str);

//
        $url = "https://cm.cmzg.vip/app/index.php?i=$pid&c=entry&do=api_record_data_set&m=$table&themeid=$aid&recordid=$recordid&data=$dataStr";
        Log::info("java-to-php3-last：" . $url);
        $http_data = $this->curl_request2($url, $method = 'get', $params = [], $header = [], $type = 'https');
        //return $http_data;
        return $url . ":" . $http_data;
    }

    public function encodeURIComponent($str)
    {
        $revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')', '%20' => '+');
        return strtr(rawurlencode($str), $revert);
    }


    //陈鑫需要一个东西包一下phpobs
    public function phpobs(Request $request)
    {
        //start_time=2025-05-01&end_time=2025-05-02
        $start_time = $request->get('start_time');
        $end_time = $request->get('end_time');
        //
        $api_url = "http://obs.cmzg.vip/qncloud/export/orders/export/?start_time=$start_time&end_time=$end_time";
        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');
        //$jsonObject = json_decode($http_data);
        return $http_data;
    }

    //
    //refundpay项目支付回调后-> php查库 ->通知夏天;
    //toCallPHPupdateTuanOfNewOrder
    //post请求主要是订单id
    public function toCallPHPupdateTuanOfNewOrder(Request $request)
    {
        $og = $request->post();
        $db_detailid = $og['cmzgOrderid'];
        //$db_detailid = substr($page_detailid,1);

        $arr2 = $this->bigServiec->findRecordByxx($db_detailid);

        $status_pay = $arr2['status']; //改成这个
        $status_refund = $isrefund = $arr2['isrefund']; //是否退款要更新
        $fee = $arr2['fee'];
        $refund_fee = $fee; //其实就是支付的钱 $arr2['fee']
        $cmzg_refund_status = 0;  //默认退款状态是0
        //
        if (-1 == $status_pay && 1 == $isrefund) {
            $cmzg_refund_status = 1;
        }
        //支付状态 + 团员状态 + 核销状态
        $pid = $arr2['pid']; // 所属团长
        $noid = $arr2['noid'];
        $status_finish = $arr2['isfinish'];  //0 拼团中 1已成团
        $num = $arr2['num'];
        $need_num = $arr2['neednum'];
        $has_num = $arr2['hasnum'];
        $remark = $arr2['remark'];
        $source_openid = $arr2['sourceid'];
        $verify_time = $arr2['verifytime'];
        $verify_time = date("Y-m-d H:i:s", $verify_time);
        $verify_openid = $arr2['verifyopenid'];
        $birthday = $arr2['birthday'];

        $params_a = [
            'nid' => $nid,
            "status_pay" => $status_pay,
            "status_refund" => $status_refund,
            "refund_fee" => $refund_fee,

            "pid" => $pid,
            "noid" => $noid,
            "status_finish" => $status_finish,
            "num" => $num,
            "need_num" => $need_num,
            "has_num" => $has_num,
            "remark" => $remark,
            "source_openid" => $source_openid,
            "verify_time" => $verify_time,
            "verify_openid" => $verify_openid,

            //退款的信息
            "cmzg_refund_status" => $cmzg_refund_status,

            "birthday" => $birthday,

        ];
        //测试与修复。
        $params_a = json_encode($params_a);
        $header = ['Content-Type: application/json'];
        //新订单接口
        $xia_url = "https://gateway.cmxz.com.cn/oa/api/new/order/";
        if ($test == 'yes') {
            return $params_a;
        }
        $http_data = $this->curl_request2($xia_url, $method = 'put', $params_a, $header, $type = 'https');
        //测试的时候看下返回值
        return $params_a;
    }

    //findThemebyid 服务层 已经有了,
    //为了找活动时间
    public function xufei(Request $request)
    {
        $result = array();

        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $type = $request->get('type');
        $phone = $request->get("phone");


//        if (strlen($phone) === 11) {
//            //echo "是11位";
//        } else {
//            //echo "不是11位";
//            $result['code'] = 2;
//            $result['okvip'] = 'no';
//            $result['tips'] = "$phone 不是会员,肯定超期了";
//            return json_encode($result);
//        }


        //是否代理
//        $phonearr['phone'] = $phone;
//        $params_j = json_encode($phonearr);
//        $header = ['Content-Type: application/json'];
//        $urlproxy = "https://ht.i01.com.cn/shopkeeper/wxapp_api/v1/out/findpidsbyphone";
//        $http_data = $this->curl_request2($urlproxy, $method = 'post', $params_j, $header, $type = 'https');
//        $http_r = json_decode($http_data, true);
//        $in_data = $http_r['data'];  //是个数组 里面有一个对象 或者0 个对象；
//        $count = count($in_data);




        $r = $this->bigServiec->findThemebyid($aid);
        $knownTimestamp = 1743436800; // 已知的时间戳，例如 2025-04-01 00:00:00 UTC
        $knownTimestamp = $r['begintime']; // 已知的时间戳，例如 2025-04-01 00:00:00 UTC
        $currentTimestamp = time();   // 当前时间戳
        $secondsIn365Days = 365 * 24 * 60 * 60; // 365天的总秒数
        // 计算当前时间与已知时间的差值（秒）
        $diffInSeconds = $currentTimestamp - $knownTimestamp;
        // 判断是否超过365天
        if ($diffInSeconds > $secondsIn365Days) {
            $msg365 = "已超过365天";
            $oktime365 = 'no';
        } else {
            $msg365 = "未超过365天，还剩 " . ceil(($secondsIn365Days - $diffInSeconds) / (24 * 3600)) . " 天";
            $oktime365 = 'yes';
        }

        $secondsIn300Days = 300 * 24 * 60 * 60; // 365天的总秒数
        $diffInSeconds_300 = $currentTimestamp - $knownTimestamp;
        if ($diffInSeconds_300 > $secondsIn300Days) {
            $msg300 = "已超过300天";
            $oktime300 = 'no';
        } else {
            $msg300 = "未超过300天，还剩 " . ceil(($secondsIn365Days - $diffInSeconds) / (24 * 3600)) . " 天";
            $oktime300 = 'yes';
        }

        $result['dd'] = ceil(($secondsIn365Days - $diffInSeconds) / (24 * 3600));
        $result['msg365'] = $msg365;
        $result['msg300'] = $msg300;
        $result['oktime365'] = $oktime365;
        $result['oktime300'] = $oktime300;

        //是否会员。 其实可以 第二步获取。
        $phonearr['phone'] = $phone;
        $params_j = json_encode($phonearr);
        $header = ['Content-Type: application/json'];
        $urlvip = "https://ht.i01.com.cn/shopkeeper/wxapp_api/v1/out/findwechatuserandvip_byphone";
        $http_data = $this->curl_request2($urlvip, $method = 'post', $params_j, $header, $type = 'https');

        $http_r = json_decode($http_data, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            die('JSON 解析失败: ' . json_last_error_msg());
        }
        $okvip = $http_r['okvip'] ?? "no";
        $result['okvip'] = $okvip;


        $s = $this->isdaili($pid);
        if ($s == 2 ) {
            //代理
            $result['code'] = 1;
            $result['tips'] = '代理';
            return json_encode($result);
        }


        if ($oktime365 == "no") { //超过了365天
            if ($okvip == "yes") {
                $result['code'] = 1;
                $result['tips'] = "超过了365天，$phone 是会员";
                return json_encode($result);
            } else {
                $result['code'] = 2;
                $result['tips'] = "超过了365天，$phone 不是会员";
                return json_encode($result);
            }
        }

        if ($oktime300 == "no") { //超过了300天 临期
            if ($okvip == "yes") {
                $result['code'] = 1;
                $result['tips'] = "超过了300天，$phone 是会员";
                return json_encode($result);
            } else {
                $result['code'] = 3;
                $result['tips'] = "超过了300天，$phone 不是会员";
                return json_encode($result);
            }
        }

        //没有超过 300天
        $result['code'] = 1; //没有超过300天
        $result['tips'] = "没有超过300天";
        return json_encode($result);
    }


    public function jiaoyi(Request $request)
    {
        $detailid = $request->get("detailid");
        $arr1 = $this->bigServiec->findOrderBydetailid($detailid);
        return json_encode($arr1);
    }

    public function test_xufei(Request $request)
    {
        $pid = $request->get("pid");

        return $this->isdaili($pid);
    }

    public function isdaili($pid){

        $api_url = "https://gateway.cmxz.com.cn/oa/api/platform/info";

        $params_a = [
            'pid' => $pid
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');


        $jsonObject = json_decode($http_data);
        //$name = $jsonObject->data->pay_method->name;
        $s = $jsonObject->data->pay_method->status;
        return $s;
    }

    //升级成团长
    public function uptuanzhang($pid,$aid,$recordid,$intype){
        if(!isset($intype)){
            $r['coke']='401';
            $r['msg']='intype 没有传入。不知道是哪个入口调的pc 还是mp';
            return "";
        }
        if("mp"==$intype){
            //入参什么都不做
        }else{
            //不是小程序就是pc
            $recordid = substr($recordid, 1);
        }
        //唯一一个入参方式非 记录
        Log::info("uptuanzhang:".$pid.'-'.$aid.'-'.$recordid );
        $arr2 = $this->bigServiec->findRecordByxx($recordid);
        $noid = $arr2['noid'];  //先记录原来的
        if($arr2['pid'] == 0 ){ //团长订单
            $r['message']['code']=1 ; //出错了
            $r['message']['msg']='只有团员才能升级成团长';
            return json_encode($r);
        }
        $url = "https://cm.cmzg.vip/app/index.php?i=$pid&c=entry&themeid=$aid&do=api_record_cmzgup&m=water_salegroup3&recordid=$recordid";
        $http_data = $this->curl_request2($url, $method = 'get', $params=[], $header=[], $type = 'https');
        //升级后

        $arr2_new = $this->bigServiec->findRecordByxx($recordid); //升级后的自己
        $noid_new = $arr2_new['noid'];  //新团的
        $arr_noid_new= $this->bigServiec->findRecordByNoid($noid_new); //新团订单，且肯定只有一个订单
        $len_new = count($arr_noid_new);
        $xia_new = $this->updateOnidRecord($arr_noid_new);
        //-------

        $arr_noid_old = $this->bigServiec->findRecordByNoid($noid); //老团的所有订单；5个里面的4个（因为一个走了）
        $len_old = count($arr_noid_old);
        $xia_old = $this->updateOnidRecord($arr_noid_old);
        //return json_encode($arr_noid);
        return "新团订单数：".$len_new."------老团订单数：".$len_old;
    }

    //
    public function tiaotuan(Request $request){
        Log::info("tiaotuan:".json_encode($request->param()) );
        $pid = $request->get('pid');
        $aid = $request->get('aid');
        $detail = $cur_recordid = $request->get('detail');
        $group = $tuan = $request->get('group');

        //$intype =  $request->get('intype', 'mp');


        //todo 2025/11/10 新加
        $opopenid =  $request->get('opopenid', '');
        $opopname =  $request->get('opname', '');
        $oppos = $request->get('oppos', '');
        $opavatar = $request->get('opavatar', '');
        $intype =$request->get('intype', '');

        //业务1
        $arr2 = $this->bigServiec->findRecordByxx($detail);
        $noid = $arr2['noid'];  //先记录

        if($pid != $arr2['uniacid'] || $aid != $arr2['themeid'] ){
            $arr['message']['code']=1;
            $arr['message']['msg']="所选活动不正确";
            return json_encode($arr);
        }

        if($noid == $group){
            $arr['message']['code']=1;
            $arr['message']['msg']="已经在 $group 里了";
            return json_encode($arr);
        }

        $url = "https://cm.cmzg.vip/app/index.php?i=$pid&c=entry&themeid=$aid&do=api_record_cmzgadjust&m=water_salegroup3&detail=$detail&group=$group";
        $http_data = $this->curl_request2($url, $method = 'get', $params=[], $header=[], $type = 'https');
        $obj = json_decode($http_data); //这是对象，不是数组
        $some_arr = json_decode($http_data,true);
        $message = $some_arr['message']['msg']; //只有'success' 才算成功
        $code = $some_arr['message']['code'];
        if($code == 1){
            return $http_data;
        }
        //$msg = $message['msg'];
        //var_dump($some_arr);
        //return 22;
        //todo 调团成功 tologtiaotuan( );
        //操作要的头像 很有可能需要后端php 再查一次
        $this->tologtiaotuan($pid,$aid,$detail,$noid,$group,$opopenid,$opopname,$oppos,$opavatar,$intype);

        usleep(1800000);  //睡眠1.8秒

        $arr_noid = $this->bigServiec->findRecordByNoid($noid); //旧团订单
        $xia_r = $this->updateOnidRecord($arr_noid);
        //业务2
        $arr_noid_2 = $this->bigServiec->findRecordByNoid($group); //新团订单
        $xia_r2 = $this->updateOnidRecord($arr_noid_2);
        //尝试看下自己的订单
        $arr2_2 = $this->bigServiec->findRecordByxx($detail);  //上线的时候  可以去掉
        $noid_2 = $arr2_2['noid'];  //先记录

        $str = "订单号：".$detail."的老noid是:".$noid."---新的noid是:".$noid_2."入新团的参数是:".$group;
        //$r['str']=$str;
        $r['dy_url']= $http_data;

        //$r['old']= $arr_noid;
        //$r['new']= $arr_noid_2; //新的团 含刚过去的自己
        //$r['xia_r'] = $xia_r;
        //$r['xia_r2'] = $xia_r2;
        return $http_data;
        //return json_encode($r);

    }

    //toTellPHP
    public function totellphp(Request $request){
        Log::info("totellphp:".json_encode($request->param()) );
        $pid = $request->get('pid');
        $aid = $request->get('aid');
        $tid2 = $request->get('tid2');
        $arr['code'] = $pid;
        return json_encode($arr);
    }

    private function find_f_name($uniacid,$themeid,$f_openid)
    {
        $arr = $this->bigServiec->find_f_name($uniacid,$themeid,$f_openid);  //上线的时候  可以去掉
        return $arr;
    }


    //api接口给CX用的（用于调团的搜索）
    //$key
    public function findrecordbykey(Request $request){
        Log::info("findrecordsbyx:".json_encode($request->param()) );
        $pid = $request->get('pid');
        $aid =  $request->get('aid');
        $key = $request->get('key');
        $arr = $this->bigServiec->findrecordsbykey($pid,$aid,$key);
        return json_encode($arr);
    }


    //https://back.screen.cmxz.com.cn/index.php/test_tologtiaotuan?pid=1001&aid=2001&detail=pt&noid=123456&group=5001&opopenid=oAbc123xyz_openid&opopname=张经理&oppos=区域主管&opavatar=https://example.com/avatar.jpg&intype=mp
    public function test_tologtiaotuan(Request $request){
        // 从请求中获取所有需要的参数（支持 GET / POST）
        $pid      = $request->param('pid');      // 推荐用 param() 兼容 GET/POST
        $aid      = $request->param('aid');
        $detail   = $request->param('detail');
        $noid     = $request->param('noid');
        $group    = $request->param('group');
        $opopenid = $request->param('opopenid');
        $opopname = $request->param('opopname');
        $oppos    = $request->param('oppos');
        $opavatar = $request->param('opavatar');
        $intype   = $request->param('intype');

        // 调用私有方法处理逻辑
        $result = $this->tologtiaotuan(
            $pid,
            $aid,
            $detail,
            $noid,
            $group,
            $opopenid,
            $opopname,
            $oppos,
            $opavatar,
            $intype
        );
        Log::info('测试调团'.$result);
    }



    // php调完团后 通知java 去DB 记录一下
    private function tologtiaotuan($pid, $aid, $detail, $noid, $group, $opopenid, $opopname, $oppos, $opavatar,$intype)
    {

        $header = ['Content-Type: application/json'];
        $arr = [];
        $arr['cmzgTiaotuanPid']=$pid;
        $arr['cmzgTiaotuanAid']=$aid;
        $arr['cmzgTiaotuanOrderid']= $detail;
        $arr['cmzgTiaotuanFromtuanid']=$noid;
        $arr['cmzgTiaotuanTotuanid']=$group;
        $arr['cmzgTiaotuanOpopenid']=$opopenid;
        $arr['cmzgTiaotuanOpname']= $opopname;
        $arr['cmzgTiaotuanOppos']= $oppos;
        $arr['cmzgTiaotuanOpavatar'] = $opavatar;
        $arr['cmzgTiaotuanintype'] = $intype;

        $params_a = json_encode($arr);
        Log::info("tologtiaotuan:".$params_a);
        $url = "https://back.smartshopkeeper.com/admin-api/pt/addtiaotuanlog";
        $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
        Log::info("java-tiaotuanf:".$http_data);
        $xr['in'] = $params_a;
        $jsonData = json_decode($http_data, true);
        $xr['out']=$jsonData;
        return json_encode($xr);
    }

}
